//根据当前时间生成文件名
function getFilename() {
	var today = new Date();
	var h = today.getHours();
	var m = today.getMinutes();
	var s = today.getSeconds();
	m = m >= 10 ? m : ('0' + m);
	s = s >= 10 ? s : ('0' + s);
	return h + "-" + m + "-" + s;
}

//截屏操作
var screenshot = {
	content: document.createElement("canvas"),
	data: '',
	saveScreenshot: function(key) {
		var image = new Image();
		image.onload = function() {
			var canvas = screenshot.content;
			canvas.width = image.width;
			canvas.height = image.height;
			var context = canvas.getContext("2d");
			context.drawImage(image, 0, 0);

			// 保存图片
			var link = document.createElement('a');
			link.href = screenshot.data;
			link.download = key + ".png";
			link.click();
			screenshot.data = '';
		};
		image.src = screenshot.data;
	},
	work: function(filename) {
		chrome.tabs.captureVisibleTab({
			format: 'png'
		}, function(screenshotUrl) {
			screenshot.data = screenshotUrl;
			// 保存screenshotUrl， image信息，默认使用png格式
			screenshot.saveScreenshot(filename);
		});
	}
};

//IntervalID，用于控制任务循环执行
var IntervalID = -1;
//循环运行状态
var status = false;
//循环间隔时长
var time = -1;
//是否刷新网页
var refresh = false;


function loop() {
	if (IntervalID != -1) {
		clearInterval(IntervalID);
		IntervalID = -1;
	}
	if (time == -11) {
		//单次截屏，不循环
		work();
	} else if (time >= 1000) {
		IntervalID = setInterval(work, time);
		status = true;
	} else {
		//clearInterval(IntervalID);
		//IntervalID = -1;
		time = -1;
		status = false;
	}
}

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
	if (message.type == 'screenshot') {
		time = message.time;
		refresh = message.refresh;
		loop();
	}
	// 					else if (message.type == 'status') {
	// 						// sendResponse(getParams());
	// 					}
	sendResponse({
		status: status,
		time: time,
		refresh: refresh
	});
});


//监听页面加载完成回调
// chrome.tabs.onUpdated.addListener(function(id, info, tab) {
// 	if (tab.status === 'complete') {
// 		if (refresh && loopTime > 1000) {
// 			console.log("onUpdated-complete-refresh");
// 			screenshot.work(getFilename());
// 		}
// 	}
// });

//执行一次截屏操作
function work() {
	if (refresh) {
		//刷新一次网页，网页刷新完毕后会有截屏回调
		chrome.runtime.sendMessage('refresh');
	} else {
		//不刷新网页，直接截屏
		screenshot.work(getFilename());
	}
}
